package com.tc.juc.n4;

import lombok.extern.slf4j.Slf4j;

/**
 * @Auther: tianchao
 * @Date: 2021/10/4 13:56
 * @Description:
 */
@Slf4j
public class DeadLockTest {
    public static void main(String[] args) {
        Chopstick c1 = new Chopstick("筷子1");
        Chopstick c2 = new Chopstick("筷子2");
        Chopstick c3 = new Chopstick("筷子3");
        Chopstick c4 = new Chopstick("筷子4");
        Chopstick c5 = new Chopstick("筷子5");
        People people1 = new People("教授1", c1, c2);
        People people2 = new People("教授2", c2, c3);
        People people3 = new People("教授3", c3, c4);
        People people4 = new People("教授4", c4, c5);
        People people5 = new People("教授5", c5, c1);
        people1.start();
        people2.start();
        people3.start();
        people4.start();
        people5.start();


    }






    /**
     * 简单死锁
     */
    public static void testSimple(){
        Object A = new Object();
        Object B = new Object();
        Thread t1 = new Thread(() -> {
            synchronized (A) {
                log.debug("lock A");
                sleep(1);
                synchronized (B) {
                    log.debug("lock B");
                    log.debug("操作...");
                }
            }
        }, "t1");
        Thread t2 = new Thread(() -> {
            synchronized (B) {
                log.debug("lock B");
                sleep(2);
                synchronized (A) {
                    log.debug("lock A");
                    log.debug("操作...");
                }
            }
        }, "t2");
        t1.start();
        t2.start();
    }

    private static void sleep(int i) {
        try {
            Thread.sleep(i*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
@Slf4j
class People extends Thread{
    Chopstick left;
    Chopstick right;


    public People(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
       while (true){
           //尝试获得左手筷子
           synchronized (left){
               //尝试获得右手筷子
               synchronized (right){
                   eat();
               }
           }
       }
    }
    public void eat(){
        log.info("eatting...");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/**
 * 筷子类
 */
@Slf4j
class Chopstick{
    String name;

    public Chopstick(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "筷子{" +
                "name='" + name + '\'' +
                '}';
    }
}
